/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ile.Modelo;

import ile.DAO.CrearBaseDeDatos;
import java.awt.Image;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
 *
 * @author
 */
public class CargarImagenes {

    //variables para conexión a base de datos
    public static Connection CONEXION;
    private static Statement sentencia;
    static ResultSet rs;
    public static String host_bd = "localhost";
    public static String user = "root";
    public static String clave = "root";
    private Image data;
    public static Connection cm;
//     EntityManagerFactory cm= (EntityManagerFactory) DataSource.getEntityManager();

    public CargarImagenes() {
        cm = CargarImagenes.conectate();
    }

//     
//    public static void main(String [] arg){
//        CargarImagenes m=new CargarImagenes();
//        m.guardarfoto("2","C/pauly/home/Escritorio/Logos/dibujostaxi.jpg");
//    }
    public void guardarfoto(String nombre, String foto) {
        {
            FileInputStream fis = null;
            try {
                File file = new File(foto);
                fis = new FileInputStream(file);

                PreparedStatement pstm = cm.prepareStatement("insert into "
                        + " material (id, foto) " + " values(?,?)");
                pstm.setString(1, nombre);
                pstm.setBinaryStream(2, fis, (int) file.length());
                pstm.execute();
                pstm.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(CargarImagenes.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException e) {
                System.out.println(e);
            } finally {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(CargarImagenes.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    private Image ConvertirImagen(byte[] bytes) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; // File or InputStream
        ImageInputStream iis = ImageIO.createImageInputStream(source);
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
        return reader.read(0, param);
    }

    public Image getfoto(String id) throws SQLException {
        try {
            PreparedStatement pstm = cm.prepareStatement("SELECT "
                    + " foto "
                    + " FROM material "
                    + " where id = ? ");
            pstm.setString(1, id);
            ResultSet res = pstm.executeQuery();
            int i = 0;
            while (res.next()) {
                //se lee la cadena de bytes de la base de datos
                byte[] b = res.getBytes("foto");
                // esta cadena de bytes sera convertida en una imagen
                data = ConvertirImagen(b);
                i++;
            }
            res.close();
        } catch (IOException ex) {
            Logger.getLogger(CargarImagenes.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException e) {
            System.out.println(e);
        }
        return data;
    }

    //metodo para conexión a base de datos
    public static Connection conectate() {

        try {
            try {
                Class.forName("com.mysql.jdbc.Driver");
                CONEXION = DriverManager.getConnection("jdbc:mysql://" + host_bd + ":3306/nueva", user, clave);
            } catch (SQLException e) {
                Logger.getLogger(CrearBaseDeDatos.class.getName()).log(Level.SEVERE, null, e);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(CrearBaseDeDatos.class.getName()).log(Level.SEVERE, null, ex);
        }
        return CONEXION;
    }
}
